package io.sundial.job.bind.impl;

import io.sundial.job.JobContext;
import io.sundial.job.JobParameter;
import io.sundial.job.bind.JobData;
import io.sundial.job.bind.JobField;
import io.sundial.job.bind.JobResolver;
import io.sundial.util.StrKit;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 数字 转换器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/7 17:55
 */
public class NumberResolver implements JobResolver {

    @Override
    public boolean supports(JobField field) {
        return field.type == BigInteger.class
                || field.type == BigDecimal.class
                || field.type == AtomicInteger.class
                || field.type == AtomicLong.class
                || field.type == Number.class;
    }

    @Override
    public JobParameter resolve(JobField field) {
        String value = field.value != null ? field.value.toString() : null;
        return new JobParameter(field.name)
                .setEditor("text")
                .setValue(value);
    }

    @Override
    public Object resolve(JobField field, JobData data, JobContext context) {
        String value = data.get(field.name);
        return StrKit.isEmpty(value) ? DEFAULT
                : field.type == BigInteger.class ? new BigInteger(value)
                : field.type == BigDecimal.class ? new BigDecimal(value)
                : field.type == AtomicInteger.class ? new AtomicInteger(Integer.valueOf(value))
                : field.type == AtomicLong.class ? new AtomicLong(Long.valueOf(value))
                : field.type == Number.class ? new BigDecimal(value)
                : DEFAULT;
    }
}
